const query = require("../db/mysql")
const {md5}=require("utility")
const jwt=require("jsonwebtoken")
const { success, error } = require("../modle/modle")
class Cartconunt {
    register=async (ctx)=>{
       const {username,password,nickname}=ctx.request.body;
       //判断名称是否重复
       const isHavesql=`select * from users where username="${username}"`
       //！！[]=true   ==false
       const isHave=await query(isHavesql)
       if(isHave.length){
           ctx.body=error("账号已经存在")
           return
       }
       const sql=`insert into users(username,password,nickname) values("${username}","${md5(String(password))}","${nickname}")`
       const data=await query(sql)
       if(data.affectedRows===1){
           ctx.body=success("注册成功")
       }else{
        ctx.body=error("注册失败")
       }
    }
    login=async (ctx)=>{
       const {username,password}=ctx.request.body;
       const isHavesql=`select * from users where username="${username}" and password="${md5(String(password))}"`;
       console.log(isHavesql);
       
       const isHave=await query(isHavesql)
       console.log(isHave);
       
       if(isHave.length){
        console.log(123);
         ctx.body=success({
             data:isHave[0],
             token:jwt.sign({id:isHave[0].id},"1812A"),
           
             
         },"登录成功")  
       }else{
           ctx.body=error("登录失败")
       }
    }
}
module.exports=new Cartconunt()